package com.pfzy.utildemo.activity.record.sdk.pcm.mp3;

import android.media.AudioRecord;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.pfzy.lib.config.log.MyLog;
import com.pfzy.utildemo.activity.record.sdk.pcm.mp3.lame.SimpleLame;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 数据编码线程
 */
public class DataEncodeThread extends HandlerThread implements AudioRecord.OnRecordPositionUpdateListener {
    private static final int FLAG_SWITH_FILE = 1;
    public static final boolean IS_DEBUG = false;
    private static final int PROCESS_STOP = 1;
    public static final String TAG = "DataEncodeThread";
    private EncodeThreadCallBack callBack;
    private FileOutputStream mFileOutputStream;
    private int mFlag;
    private StopHandler mHandler;
    private byte[] mMp3Buffer;
    private List<Task> mTasks;

    public interface EncodeThreadCallBack {
        void onFlushAndRelease();
    }

    public static class StopHandler extends Handler {
        private DataEncodeThread encodeThread;

        public StopHandler(Looper looper, DataEncodeThread encodeThread) {
            super(looper);
            this.encodeThread = encodeThread;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                do {
                } while (this.encodeThread.processData() > 0);
                removeCallbacksAndMessages(null);
                MyLog.logd("数据编码线程 " + "StopHandler() -> 准备 flushAndRelease ");
                this.encodeThread.flushAndRelease();
                getLooper().quit();
            }
        }
    }

    public DataEncodeThread(File file, int bufferSize, EncodeThreadCallBack call) throws FileNotFoundException {
        super(TAG);
        this.mFlag = 0;
        this.mTasks = Collections.synchronizedList(new ArrayList());
        this.mFileOutputStream = new FileOutputStream(file);
        this.callBack = call;
        this.mMp3Buffer = new byte[(int) (7200.0d + (bufferSize * 2 * 1.25d))];
    }

    @Override
    public synchronized void start() {
        super.start();
        this.mHandler = new StopHandler(getLooper(), this);
    }

    private void check() {
        if (this.mHandler == null) {
            throw new IllegalStateException();
        }
    }

    public void sendStopMessage() {
        check();
        this.mHandler.sendEmptyMessage(1);
    }

    public Handler getHandler() {
        check();
        return this.mHandler;
    }

    @Override
    public void onMarkerReached(AudioRecord recorder) {
    }

    @Override
    public void onPeriodicNotification(AudioRecord recorder) {
        processData();
    }

    public int processData() {
        if (this.mTasks.size() > 0) {
            Task task = this.mTasks.remove(0);
            short[] buffer = task.getData();
            int readSize = task.getReadSize();
            int encodedSize = SimpleLame.encode(buffer, buffer, readSize, this.mMp3Buffer);
            if (encodedSize > 0) {
                try {
                    if ((this.mFlag & 1) != 0) {
                        _loge("processData() 直接返回，碰到转换文件瞬间");
                        readSize = 0;
                    } else {
                        this.mFileOutputStream.write(this.mMp3Buffer, 0, encodedSize);
                    }
                } catch (IOException e) {
                    _loge("processData() -> exception =" + e.toString());
                    e.printStackTrace();
                }
            }
            return readSize;
        }
        return 0;
    }

    public void flushAndRelease() {
        int flushResult = SimpleLame.flush(this.mMp3Buffer);
        _logd("flushAndRelease() -> flushResult=" + flushResult);
        try {
            if (flushResult > 0) {
                this.mFileOutputStream.write(this.mMp3Buffer, 0, flushResult);
                if (this.mFileOutputStream != null) {
                    this.mFileOutputStream.close();
                }

                SimpleLame.close();

                if (this.callBack != null) {
                    this.callBack.onFlushAndRelease();
                }
            }
        } catch (IOException e) {
            _loge("flushAndRelease() -> exception =" + e.toString());
            e.printStackTrace();
        } catch (Throwable th) {
            throw th;
        }
    }

    public void addTask(short[] rawData, int readSize) {
        this.mTasks.add(new Task(rawData, readSize));
    }

    public class Task {
        private short[] rawData;
        private int readSize;

        public Task(short[] rawData, int readSize) {
            this.rawData = (short[]) rawData.clone();
            this.readSize = readSize;
        }

        public short[] getData() {
            return this.rawData;
        }

        public int getReadSize() {
            return this.readSize;
        }
    }

    public void changeToNewRecordPath(String fileName) {
        long startTime = System.currentTimeMillis();
        _logd("enter refreshFilePatchName() filePath= " + fileName);
        try {
            this.mFlag |= FLAG_SWITH_FILE;
            if (this.mFileOutputStream != null) {
                this.mFileOutputStream.close();
            }
            this.mFileOutputStream = new FileOutputStream(fileName);
            this.mFlag &= -2;
        } catch (Exception e) {
            _loge("refreshFilePatchName() 发生异常 =" + e.toString());
        }
        _logd(" refreshFilePatchName() over 耗时=" + (System.currentTimeMillis() - startTime) + " \t " + fileName);
    }

    private void _logd(String msg) {
        MyLog.logd("数据编码线程 " + msg);
    }

    private void _loge(String msg) {
        MyLog.loge("数据编码线程 " + msg);
    }
}
